<script>
import request from "../../../utils/request"
import store from "../../../store"
import { userActionType } from "../../../store/modules/user"
import empty from "../../../components/empty.vue"
import UniLoadMore from "../../../uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue"
import { showModal, showToast } from "../../../utils"
import { handleUrlParams } from "../../../utils"
import vocabularyDetail from "../../../components/vocabularyDetail.vue"
import websocket from "@/utils/websocket"
import studyRoomFloat from "@/components/studyRoomFloat/index.vue"
import { vocabularyLearningActionType } from "@/store/modules/vocabularyLearning"

export default {
  name: "index",
  components: { UniLoadMore, empty, vocabularyDetail, studyRoomFloat },
  data() {
    return {
      currentTab: "wrong",
      tabList: [
        { value: "wordList", label: "已学" },
        { value: "wrong", label: "错词" },
        { value: "favorite", label: "收藏" },
      ],
      pagination: {
        current: 1,
        size: 10,
      },
      total: 0,
      list: [],
      loadMoreStatusText: "more",
      isEmpty: false, //一条数据都没有则展示空状态
    }
  },
  computed: {
    planInfo: () => store.getters[vocabularyLearningActionType.getters.planInfo],
		userSelectExamId: () => store.getters[userActionType.getters.userSelectExamId],
  },
  onLoad(query) {
    if (query.currentTab) {
      this.currentTab = query.currentTab
    }
  },
  async onShow() {
    websocket.trackCurrentPage("我的单词本").catch(() => {})
    //获取当前计划
    if (!this.userSelectExamId) {
      await store.dispatch(userActionType.action.examInfo, { jumpToSelectExamPage: true })
    }
		if (!this.planInfo.planId) {
			await store.dispatch(vocabularyLearningActionType.actions.planInfo, {
				showLoading: true
			})
		}
    //尚未制定计划
    if (!this.planInfo.planId) {
      uni.redirectTo({
        url: "/vocabulary/pages/makeLearningPlan/thesaurus",
      })
    }
    //加载数据
    await this.refresh()
  },
  methods: {
    getList() {
      return new Promise(async (resolve, reject) => {
        let url
        let queryParams = {
          ...this.pagination,
        }
        switch (this.currentTab) {
          case "wordList":
            url = "userWordsRecord/getWordsPage"
            queryParams.planId = this.planInfo.planId
            break
          case "favorite":
            url = "userFavoriteWords/getFavoriteWordsPage"
            break
          case "wrong":
            url = "userWordsRecord/getWrongWordsPage"
            queryParams.examId = this.userSelectExamId
            break
        }
        const res = await request({
          url,
          data: queryParams,
          errorHandle: true,
        })
        this.total = res.total
        //检查是否没有数据
        this.isEmpty = res.total === 0
        for (let record of res.records) {
          record.current = this.pagination.current
        }
        this.list.push(...res.records)
        //检查是否还有下一页
        if (this.list.length >= res.total) {
          this.loadMoreStatusText = "noMore"
        } else {
          this.loadMoreStatusText = "more"
        }
        resolve(res.records)
      })
    },
    //清空列表数据和分页并重新加载
    async refresh() {
      this.list = []
      this.pagination.current = 1
      this.isEmpty = false
      uni.showLoading({
        title: "加载中",
        mask: true,
      })
      await this.getList()
      uni.hideLoading()
    },
    //将单词从已收藏列表中删除
    async deleteCollection(item) {
      if (
        !(await showModal({
          title: "警告",
          content: "确定要将该单词从收藏列表中移除吗？",
        }))
      )
        return
      await request({
        url: "userFavoriteWords/del",
        data: {
          ids: [item.enWord],
        },
        errorHandle: true,
      })
      showToast.success("删除成功")
      await this.refresh()
    },
    //再次练习
    practiceAgain(item) {
      uni.navigateTo({
        url: handleUrlParams("/vocabulary/pages/myVocabularyBook/practice", {
          planInfo: encodeURIComponent(JSON.stringify(this.planInfo)),
          type: this.currentTab,
          current: item.current,
          wordId: item.wordId,
        }),
      })
    },
  },
  //下拉刷新
  onPullDownRefresh() {
    this.refresh().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  //滑到底加载更多
  onReachBottom() {
    if (this.loadMoreStatusText === "noMore") return
    this.pagination.current++
    this.loadMoreStatusText = "loading"
    this.getList()
  },
}
</script>

<template>
  <view class="page">
    <!--		错词本 / 已背单词 / 单词收藏 标签切换-->
    <view class="tab-list">
      <view
        class="tab-item"
        v-for="item in tabList"
        :key="item.value"
        :class="[item.value === currentTab ? 'active' : 'inactive']"
        @click="
          () => {
            currentTab = item.value
            refresh()
          }
        "
      >
        <view class="text">
          <text>{{ item.label }}</text>
          <!--					单词总数-->
          <template v-if="item.value === currentTab && total !== 0">
            <text>\t</text>
            <text>{{ total }}</text>
          </template>
          <view class="active-line" v-show="item.value === currentTab"></view>
        </view>
      </view>
    </view>
    <view class="placeholder"></view>
    <empty v-if="isEmpty" height="calc(100vh - 100rpx)"></empty>
    <!--		单词列表-->
    <view class="vocabulary-list" v-else>
      <view class="vocabulary-item" v-for="(item, index) in list" :key="index">
        <view class="row">
          <!--				单词英文-->
          <view class="enWord">{{ item.enWord }}</view>
          <!--					音标-->
          <view class="phonetic">{{ item.phonetic }}</view>
        </view>
        <view class="row">
          <!--				中文解释-->
          <view class="znWord">{{ item.znWord }}</view>
        </view>
        <view class="row">
          <!--					例句-->
          <view class="enSentence" v-if="item.enSentence">{{ item.enSentence }}</view>
        </view>
        <view class="divide-line"></view>
        <view class="row btn-row">
          <!--					查看详细-->
          <view class="btn info" @click="$refs.vocabularyDetail.open(item.enWord, item.wordId)">查看明细</view>
          <!--					删除 (只能删除收藏的单词)-->
          <view class="btn danger" v-if="currentTab === 'favorite'" @click="deleteCollection(item)">删除</view>
          <!--					再次练习（收藏的单词不允许再次练习）-->
          <view class="btn primary" @click="practiceAgain(item)" v-if="currentTab !== 'favorite'">再次练习</view>
        </view>
      </view>
      <uni-load-more :status="loadMoreStatusText"></uni-load-more>
    </view>

    <vocabularyDetail ref="vocabularyDetail"></vocabularyDetail>
    <studyRoomFloat></studyRoomFloat>
  </view>
</template>

<style scoped lang="scss">
.page {
  background: var(--gray-background-color);
  min-height: 100vh;
  padding: {
    top: 0;
    bottom: env(safe-area-inset-bottom);
    left: 30rpx;
    right: 30rpx;
  }

  .tab-list {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    display: flex;
    background: white;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);

    .tab-item {
      width: 0;
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100rpx;

      &.active {
        > .text {
          color: var(--text-color-theme);
          font-weight: 500;
        }
      }

      > .text {
        font-size: 30rpx;
        position: relative;
      }

      .active-line {
        position: absolute;
        bottom: -20rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 50%;
        height: 6rpx;
        border-radius: 3rpx;
        background: var(--text-color-theme);
      }
    }
  }

  .placeholder {
    height: 100rpx;
  }

  .vocabulary-list {
    .vocabulary-item {
      background: white;
      margin-top: 30rpx;
      border-radius: 30rpx;
      padding: 30rpx;

      .row {
        display: flex;
        align-items: center;

        &:not(:last-child) {
          margin-bottom: 20rpx;
        }

        &.btn-row {
          justify-content: space-between;
        }
      }

      .divide-line {
        height: 2rpx;
        background: var(--border-color);
        margin: 20rpx 0;
      }

      .enWord {
        font-size: 36rpx;
        color: var(--text-color);
        font-weight: bold;
      }

      .phonetic {
        font-size: 32rpx;
        color: var(--text-color-light);
        margin-left: 30rpx;
      }

      .znWord {
        font-size: 32rpx;
        color: var(--text-color-light);
      }

      .enSentence {
        font-size: 32rpx;
        //文本溢出部分自动加省略号
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .btn {
        font-size: 30rpx;
        height: 60rpx;
        line-height: 60rpx;
        padding: 0 40rpx;
        border-radius: 30rpx;

        &.primary {
          background: var(--theme-color);
          color: var(--text-color-white);
        }

        &.info {
          background: var(--gray-background-color);
          border: 2rpx solid var(--border-color);
        }

        &.danger {
          background: #c0392b;
          color: white;
        }
      }
    }
  }
}
</style>
